package com.example.snashuitraverl.demos.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.snashuitraverl.demos.common.ErrorCode;
import com.example.snashuitraverl.demos.contant.UserConstant;
import com.example.snashuitraverl.demos.domain.DTO.UserDto;
import com.example.snashuitraverl.demos.domain.User;
import com.example.snashuitraverl.demos.domain.VO.UserVO;
import com.example.snashuitraverl.demos.exception.BusinessException;
import com.example.snashuitraverl.demos.exception.ThrowUtils;
import com.example.snashuitraverl.demos.mapper.UserMapper;
import com.example.snashuitraverl.demos.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.W3CDomHandler;

import static com.example.snashuitraverl.demos.contant.UserConstant.USER_LOGIN_STATE;

/**
 * @author 32551
 * @description 针对表【user(用户表
 * )】的数据库操作Service实现
 * @createDate 2024-06-23 18:59:56
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User userLogin(String account, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(account, userPassword)) {
            return null;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        queryWrapper.eq("password", userPassword);
        User user = userMapper.selectOne(queryWrapper);
        if(user.getType()==UserConstant.Forbid_ROLE){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请联系管理员打开权限");
        }
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return user;
    }


    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setOpenID(originUser.getOpenID());
        safetyUser.setAvatural(originUser.getAvatural());
        safetyUser.setAge(originUser.getAge());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        return safetyUser;
    }

    @Override
    public int userLoginOUt(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return (User) userObj;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User User = (User) userObj;
        return User != null && User.getRole() == UserConstant.ADMIN_ROLE;
    }

    /**
     * 是否为管理员
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getRole() == UserConstant.ADMIN_ROLE;
    }

    @Override
    public User getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        User loginUserVO = new User();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 查询openID
     */
    @Override
    public User selectOpneId(String openID) {
        ThrowUtils.throwIf(StringUtils.isBlank(openID), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(openID == null, ErrorCode.PARAMS_ERROR);

        User user = userMapper.selectById(openID);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "还没有注册");
        }
        return user;
    }

    @Override
    public Page<User> selectAll(UserDto userDto, HttpServletRequest request) {
        User loginUser = getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR, "还没有登录");
        ThrowUtils.throwIf(loginUser.getRole() != 1, ErrorCode.PARAMS_ERROR, "没有权限");
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        Page<User> userPageage = new Page<>(userDto.getPageNum(), userDto.getPageSize());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(user);
        Page<User> userPage = userMapper.selectPage(userPageage, userQueryWrapper);
        return userPage;
    }

    @Override
    public int updateUser(UserVO userVO, HttpServletRequest request) {
        User loginUser = getLoginUser(request);
        String openID = loginUser.getOpenID();
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User openID1 = userMapper.selectOne(new QueryWrapper<User>().eq("openID", openID));
        if (openID1 == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        BeanUtils.copyProperties(userVO, loginUser);

        int update = userMapper.update(null, new LambdaUpdateWrapper<User>()
                .eq(User::getOpenID, openID1.getOpenID())
                .set(User::getAge, userVO.getAge())
                .set(User::getPassword, userVO.getPassword())
                .set(User::getGender, userVO.getGender())
                .set(User::getPhone, userVO.getPhone())
                .set(User::getAccount, userVO.getAccount())
                .set(User::getEmail, userVO.getEmail())
                .set(User::getAvatural, userVO.getAvatural())
                .set(User::getAddress, userVO.getAddress())
        );
        if ((update!=1)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return update ;
    }
    @Override
    public int updateAliUser(User user) {
        int update = userMapper.update(null, new LambdaUpdateWrapper<User>()
                .eq(User::getOpenID, user.getOpenID())
                .set(User::getAge, user.getAge())
                .set(User::getPassword, user.getPassword())
                .set(User::getGender, user.getGender())
                .set(User::getPhone, user.getPhone())
                .set(User::getAccount, user.getAccount())
                .set(User::getEmail, user.getEmail())
                .set(User::getAvatural, user.getAvatural())
                .set(User::getAddress, user.getAddress())
        );
        if ((update!=1)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return update ;
    }

    @Override
    public int forbidLogin(String account) {

        User Account = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        if(StringUtils.isBlank(Account.getAccount())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"没有查询到用户openID");
        }
        int update = userMapper.update(null, new LambdaUpdateWrapper<User>()
                .eq(User::getAccount, Account.getAccount())
                .set(User::getType, UserConstant.Forbid_ROLE));

        if(update==-1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"修改失败");
        }
        return update;
    }

    @Override
    public int openUserLogin(String account) {
        User Account = userMapper.selectOne(new QueryWrapper<User>().eq("account", account));
        if(StringUtils.isBlank(Account.getAccount())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"没有查询到用户openID");
        }
        int update = userMapper.update(null, new LambdaUpdateWrapper<User>()
                .eq(User::getAccount, Account.getAccount())
                .set(User::getType, UserConstant.User_ROLE));
        if(update==-1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"修改失败");
        }
        return update;
    }
}




